package com.tds.springbootdemo2.util;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * Copyright (C) 2014-2023 天津紫藤科技有限公司. Co. Ltd. All Rights Reserved.
 *
 * @author tongdashuai
 * @version 1.0
 * @description
 * @module
 * @date 2024/10/10 16:20
 */
public class JasyptUtil {

    /**
     * 加密
     */
    public static String encrypt(String password, String value) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        String result = encryptor.encrypt(value);
        return result;
    }

    /**
     * 解密
     */
    public static String decrypt(String password, String value) {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(password);
        config.setAlgorithm("PBEWithMD5AndDES");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize("1");
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
        String result = encryptor.decrypt(value);
        return result;
    }

    public static void main(String[] args) {
        // cat .bash_profile查看DECRYPT_KEY(su ziteng)
//        // 加密
//        String encrypt = encrypt("password", "ziteng");
//        System.out.println(encrypt);
        // 解密
        String encrypt = "njlVRJAtHwyWEsPmlbEheMeceCj2wEGc";
//        username: ENC(OOodmYHZ4OhGLN04IoXDrpDLrz+DK4vs7UTVk5eGUAs=)
//        password: ENC(rMCbhuvKN+ntI5ru0fPE77137Y1XkABhjWfmuQYhJWw=)

        encrypt = "rMCbhuvKN+ntI5ru0fPE77137Y1XkABhjWfmuQYhJWw=";
        String pass = "canteen";
//        pass = "zity-intelligent-hardware"; // 校园
        String decrypt = decrypt(pass, encrypt);
        System.out.println(decrypt);
    }
}
